<?php
namespace App\Logic\Plat\Shopify;
use App\Models\Basics\SysPlat;
use App\Models\Basics\SysPlatCountry;
use App\Models\CustomerDelivery\CustomerOrder;
use App\Models\Product\ProductShopifySku;
use App\Models\Shopify\ShopifyLogs;
use App\Models\Shopify\ShopifyOrder;
use App\Models\Shopify\ShopifyOrderCondition;
use Illuminate\Support\Facades\DB;

class GrabOrders extends GrabCommon{

    const GRAB_ORDERS_INTERVAL = 3600 * 24 * 30 * 12;

    /**
     * 返回您在指定时间段内所创建或更新的订单。
     * @param string $shop 'UNG','ORG'
     */
    public static function getShopifyOrder($shop = 'UNG'){

        //dd('shopify-API!!!');

        //参数
        if(!in_array($shop, self::$_shop)) die(0);
        $con = self::_matchOrderListOrdersCondition($shop);

        //获取订单(带分页数据)
        $client = self::getRequestClient($shop);
        $pagination = $client->getOrderManager()->paginate($con);
        $orderList = $pagination->current(); //当前,第一页数据

        //存在分页(合并数据)
        while ($pagination->hasNext()) {
            $nextPageInfo = $pagination->getNextPageInfo();
            $nextPagedata = $pagination->current($nextPageInfo); //下一页数据
            $orderList = array_merge($orderList, $nextPagedata); //合并分页数据(总订单)
        }

        if ($orderList) {
            //创建shopify订单
            self::_extractShopifyOrders($orderList);

            //更新最后执行时间 (下次开始时间)
            ShopifyOrderCondition::upNextStartTime($shop, strtotime($con['created_at_max']));

            //添加运行日志
            $totalCount = count($orderList) ?? 0; //执行条数
            ShopifyLogs::logs(ShopifyLogs::$logOrderSync, date('Y-m-d H:i:s', $con['start_time']).',['. $totalCount .']条,shopify订单同步成功!');
        }
    }

    /**
     * 匹配Orders参数（getShopifyOrder->1）
     * @param $shop
     * @return array|null
     */
    private static function _matchOrderListOrdersCondition($shop){

        $createdAtMin = ShopifyOrderCondition::getNextStartTime($shop);
        if(!$createdAtMin) return null;

        $con = [];
        $con['created_at_min'] = getDateFormat(date('Y-m-d H:i:s', $createdAtMin), 'PRC', 'Y-m-d\TH:i:sP');
        $createAtMax = $createdAtMin + self::GRAB_ORDERS_INTERVAL;
        if($createAtMax > time()){
            $createAtMax = time();
        }
        $con['created_at_max'] = getDateFormat(date('Y-m-d H:i:s', $createAtMax), 'PRC', 'Y-m-d\TH:i:sP');
        $con['limit'] = 50;
        $con['status'] = 'any';
        $con['fields'] = 'id,email,created_at,name,total_line_items_price,total_discounts,total-price,currency,line_items,shipping_lines,shipping_address,fulfillments,note';
        $con['start_time'] = $createdAtMin;

        //验证
        $min = $con['created_at_min'];
        $max = $con['created_at_max'];
        if(strtotime($min) >= strtotime($max) || strtotime($min) >= (strtotime($max)-120)) die('stop!');

        return $con;
    }

    /**
     * 创建shopify订单（getShopifyOrder->2）
     * @param $orderList
     * @param int $erpSync
     */
    private static function _extractShopifyOrders($orderList, $erpSync = 1){
        try{
            DB::connection('mysql_shopify')->beginTransaction();
            $n = 0;
            if ($orderList) {
                foreach ($orderList as $key => $val){

                    $orderNo = $val->getName();
                    $shopifyOrderObj = ShopifyOrder::query()->where('order_id', $orderNo)->first();
                    if ($shopifyOrderObj) continue;

                    //订单
                    $order = [];
                    $order['order_api_id'] = $val->getId();
                    $order['order_id'] = $orderNo;
                    $order['email'] = $val->getEmail();
                    $order['purchase_at'] = $val->getCreatedAt()->getTimestamp();
                    $order['total_line_items_price'] = $val->getTotalLineItemsPrice();
                    $order['total_discounts'] = $val->getTotalDiscounts();
                    $order['total_price'] = $val->getTotalPrice();
                    $order['currency'] = $val->getCurrency();
                    $order['note'] = $val->getNote();
                    $order['erp_sync'] = $erpSync;
                    $shippingLinesTitle = '';
                    foreach($val->getShippingLines() as $_k => $shippingLines){
                        $shippingLinesTitle = $shippingLines->getTitle() ?? '';
                    }
                    $order['shipping_lines_title'] = $shippingLinesTitle;

                    //订单明细
                    $orderItem = [];
                    foreach($val->getLineItems() as $_k => $lineItems){
                        $orderItem[$_k]['items_id'] = $lineItems->getId();
                        $orderItem[$_k]['product_id'] = $lineItems->getProductId();
                        $orderItem[$_k]['title'] = $lineItems->getTitle();
                        $orderItem[$_k]['sku'] = $lineItems->getSku();
                        $orderItem[$_k]['variant_id'] = $lineItems->getVariantId();
                        $orderItem[$_k]['variant_title'] = $lineItems->getVariantTitle();
                        $orderItem[$_k]['name'] = $lineItems->getName();
                        $orderItem[$_k]['quantity'] = $lineItems->getQuantity();
                        $orderItem[$_k]['price'] = $lineItems->getPrice();
                        $orderItem[$_k]['total_discount'] = $lineItems->getTotalDiscount();
                        $totalDiscount = 0;
                        foreach($lineItems->getDiscountAllocations() as $total_discount){
                            $totalDiscount += $total_discount->getAmount();
                        }
                        $orderItem[$_k]['discount_allocations'] = $totalDiscount;
                        $orderItem[$_k]['erp_sync'] = $erpSync;
                    }

                    //订单地址
                    $orderAddress = [];
                    $shippingAddress = $val->getShippingAddress();
                    $orderAddress['name'] = $shippingAddress->getName();
                    $orderAddress['country'] = $shippingAddress->getCountry();
                    $orderAddress['country_code'] = $shippingAddress->getCountryCode();
                    $orderAddress['province'] = $shippingAddress->getProvince();
                    $orderAddress['city'] = $shippingAddress->getCity();
                    $orderAddress['address1'] = $shippingAddress->getAddress1();
                    $orderAddress['address2'] = $shippingAddress->getAddress2();
                    $orderAddress['zip'] = $shippingAddress->getZip();
                    $orderAddress['phone'] = $shippingAddress->getPhone();

                    //创建shopify订单
                    $shopifyOrder = ShopifyOrder::query()->create($order);
                    $shopifyOrder->shopify_orders_items()->createMany($orderItem);
                    $shopifyOrder->shopify_orders_address()->create($orderAddress);
                    if (!$shopifyOrder) {
                        DB::connection('mysql_shopify')->rollBack();
                    }

                    $n++;
                    echo '.........shopify-order: ['.$orderNo.'],第'.$n.'条.........'.PHP_EOL;
                }
            }

            DB::connection('mysql_shopify')->commit();
        }catch (\Exception $e){
            DB::connection('mysql_shopify')->rollBack();
            report($e);
        }
    }

    /**
     * 补录shopify订单（天）(未应用)
     * @param null $startDate
     * @param null $endDate
     * @param string $shop
     * @return false
     */
    public static function repairShopifyOrders($startDate = null, $endDate = null, $shop = 'UNG'){


        //$startDate = '2022-01-01';
        //$endDate = date('Y-m-t', strtotime($startDate));

        //日期 (默认日期：昨天)
        $startDates = is_null($startDate) == true ? date('Y-m-d',time()) : $startDate;
        $endDates = is_null($endDate) == true ? date('Y-m-d', time()) : $endDate;
        if (!strtotime($startDates) || !strtotime($endDates)) return false;

        $bof = strtotime($startDates); //开始
        $eof = strtotime($endDates); //结束
        while(true) {
            if ($bof > $eof) break;
            $time = $bof;
            $startTime = getDateFormat(date('Y-m-d 00:00:00', $time));
            $endTime = getDateFormat(date('Y-m-d 23:59:59', $time));

            $con = [];
            //$con['created_at_min'] = getDateFormat($startTime, 'PRC', 'Y-m-d\TH:i:sP');
            //$con['created_at_max'] = getDateFormat($endTime, 'PRC', 'Y-m-d\TH:i:sP');
            $con['created_at_min'] = $startTime;
            $con['created_at_max'] = $endTime;
            $con['limit'] = 200;
            $con['status'] = 'any';
            $con['fields'] = 'id,email,created_at,name,total_line_items_price,total_discounts,total-price,currency,line_items,shipping_lines,shipping_address,fulfillments,note';

            //获取订单(带分页数据)
            $client = self::getRequestClient($shop);
            $pagination = $client->getOrderManager()->paginate($con);
            $orderList = $pagination->current(); //当前,第一页数据
            //dd($orderList);

            //存在分页(合并数据)
            while ($pagination->hasNext()) {
                $nextPageInfo = $pagination->getNextPageInfo();
                $nextPagedata = $pagination->current($nextPageInfo); //下一页数据
                $orderList = array_merge($orderList, $nextPagedata); //合并分页数据(总订单)
            }

            //创建shopify订单
            self::_extractShopifyOrders($orderList);
            echo 'over: '.$startTime.PHP_EOL;
            $bof += 86400; //+1天
            sleep(2);
        }
    }

    /**
     * 同步shopify订单至ERP (消费者订单表)
     * shopify订单同步至消费者订单表
     * @param $orderIds = []
     */
    public static function syncShopifyOrder($orderIds = []){

        $platId = SysPlat::PLAT_SHOPIFY;
        DB::beginTransaction();
        try{

            //shopify未同步订单
            $query = ShopifyOrder::query()->where('erp_sync', ShopifyOrder::SYNC_NO);
            if(!empty($orderIds)){
                $query->whereIn('order_id', $orderIds);
            }
            $shopifyOrder = $query->orderBy('id')->get();

            $logData = [];
            $i = 0;
            //订单同步
            if ($shopifyOrder) {

                foreach($shopifyOrder as $order){

                    $countryCode = $order->shopify_orders_address->country_code ?? ''; //国家编码
                    if (!$countryCode) continue;
                    if ($countryCode == 'GB') $countryCode = 'UK';
                    $countryId = SysPlatCountry::getCountryId($countryCode); //国家id
                    $areaId = SysPlatCountry::getAreaIdByCountryId($countryId); //站点id
                    $order_no = $order->order_id;

                    $count = CustomerOrder::query()->where('order_no', $order_no)->count();
                    if($count > 0){
                        $order->erp_sync = ShopifyOrder::SYNC_YES; //已同步
                        $order->save();
                        continue;
                    }

                    //消费订单
                    $customerOrder = [
                        'order_no'      => $order_no,
                        'order_at'      => date('Y-m-d H:i:s', $order->purchase_at), //下单时间
                        'order_channel' => CustomerOrder::ORDER_CHANNEL_CUSTOMER, //订单渠道 (1.C端，2.B端)
                        'order_type'    => CustomerOrder::ORDER_TYPE_NORMAL, //订单类型 (1.普通订单，2.寄样订单)
                        'plat_id'       => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                        'area_id'       => $areaId,
                        'country_id'    => $countryId,
                        'country_code'  => $countryCode,
                        'order_remarks' => $order->note ?? '',
                        'shipping_lines_title' => $order->shipping_lines_title ?? ''
                    ];

                    //订单明细
                    $customerOrderDetail = [];
                    $itemFlag = false;
                    foreach($order->shopify_orders_items as $item){
                        $goodsCode = ProductShopifySku::getValueByCode($item->sku, 'psku_id'); //通过平台SKU匹配公司产品(psku_id)
                        if(!$goodsCode) {
                            if(!$itemFlag){
                                $itemFlag = true;
                            }
                            $item->erp_sync = ShopifyOrder::SYNC_ERROR; //异常：匹配失败
                            $item->save();
                            continue;
                        }
                        $item->erp_sync = ShopifyOrder::SYNC_YES;//已同步
                        $item->save();

                        $customerOrderDetail[] = [
                            'plat_id'   => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                            'plat_sku'  => $item->sku,
                            'psku_id'   => $goodsCode,
                            'order_num' => $item->quantity,
                            'apply_num' => 0,
                        ];
                    }
                    if($itemFlag){
                        $order->erp_sync = ShopifyOrder::SYNC_ERROR; //异常：匹配失败
                        $order->save();
                        continue;
                    }

                    //订单地址
                    $customerOrderReceiver = [
                        'country'   => $countryCode,
                        'receiver'  => $order->shopify_orders_address->name ?? '',
                        'state'     => $order->shopify_orders_address->province ?? '',
                        'city'      => $order->shopify_orders_address->city ?? '',
                        'address'   => $order->shopify_orders_address->address1 . $order->shopify_orders_address->address2 ?? '',
                        'postcode'  => $order->shopify_orders_address->zip ?? '',
                        'phone'     => $order->shopify_orders_address->phone ?? '',
                    ];

                    //创建消费订单
                    $customerOrderObj = CustomerOrder::query()->create($customerOrder);
                    $customerOrderObj->detail()->createMany($customerOrderDetail);
                    $customerOrderObj->receiver()->create($customerOrderReceiver);

                    //更新乐天订单
                    $order->erp_sync = ShopifyOrder::SYNC_YES;//同步正常
                    $order->save();

                    $logData[] = $order_no;
                    $i++;
                }
            }

            //添加日志
            $totalCount = $i;
            ShopifyLogs::logs(ShopifyLogs::$customerOrderSync, date('Y-m-d H:i:s', time()).',['. $totalCount .']条,消费者订单同步成功!', $logData);
            DB::commit();

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 同步shopify异常订单至ERP (消费者异常订单)
     * @param array $orderIds
     */
    public static function syncShopifyOrderException($orderIds = []){

        $platId = SysPlat::PLAT_SHOPIFY;
        DB::beginTransaction();
        try{

            //rakuten异常订单
            $query = ShopifyOrder::query()->where('erp_sync', ShopifyOrder::SYNC_ERROR);
            if(!empty($orderIds)){
                $query->whereIn('order_id',$orderIds);
            }
            $shopifyOrderException = $query->orderBy('id')->get();

            $logData = [];
            $i = 0;
            //订单同步
            if ($shopifyOrderException) {

                foreach($shopifyOrderException as $order){

                    $countryCode = $order->shopify_orders_address->country_code ?? ''; //国家编码
                    if (!$countryCode) continue;
                    if ($countryCode == 'GB') $countryCode = 'UK';
                    $countryId = SysPlatCountry::getCountryId($countryCode); //国家id
                    $areaId = SysPlatCountry::getAreaIdByCountryId($countryId); //站点id
                    $order_no = $order->order_id;

                    $count = CustomerOrder::query()->where('order_no', $order_no)->count();
                    if($count > 0){
                        $order->erp_sync = ShopifyOrder::SYNC_YES; //已同步
                        $order->save();
                        continue;
                    }

                    //订单
                    $customerOrder = [
                        'order_no'      => $order_no,
                        'order_at'      => date('Y-m-d H:i:s', $order->purchase_at), //下单时间
                        'order_channel' => CustomerOrder::ORDER_CHANNEL_CUSTOMER, //订单渠道 (1.C端，2.B端)
                        'order_type'    => CustomerOrder::ORDER_TYPE_NORMAL, //订单类型 (1.普通订单，2.寄样订单)
                        'plat_id'       => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                        'area_id'       => $areaId, //站点id
                        'country_id'    => $countryId, //国家id
                        'country_code'  => $countryCode, //国家编码
                        'order_remarks' => $order->note ?? '',
                        'shipping_lines_title' => $order->shipping_lines_title ?? ''
                    ];

                    //订单明细
                    $customerOrderDetail = [];
                    $itemFlag = false;
                    foreach($order->shopify_orders_items as $item){
                        $goodsCode = ProductShopifySku::getValueByCode($item->sku, 'psku_id'); //通过平台SKU匹配公司产品(psku_id)
                        if(!$goodsCode) {
                            if(!$itemFlag){
                                $itemFlag = true;
                            }
                            if($item->erp_sync != ShopifyOrder::SYNC_ERROR){
                                $item->erp_sync = ShopifyOrder::SYNC_ERROR; //异常：匹配失败
                                $item->save();
                            }
                            continue;
                        }
                        if($item->erp_sync != ShopifyOrder::SYNC_YES){
                            $item->erp_sync = ShopifyOrder::SYNC_YES;//同步正常
                            $item->save();
                        }
                        $customerOrderDetail[] = [
                            'plat_id'   => $platId, //订单平台 (0:无 1:FBA亚马逊 2:shopify 3:乐天)
                            'plat_sku'  => $item->sku,
                            'psku_id'   => $goodsCode,
                            'order_num' => $item->quantity,
                            'apply_num' => 0,
                        ];
                    }
                    if($itemFlag){
                        continue;
                    }

                    //订单地址
                    $customerOrderReceiver = [
                        'country'   => $countryCode,
                        'receiver'  => $order->shopify_orders_address->name ?? '',
                        'state'     => $order->shopify_orders_address->province ?? '',
                        'city'      => $order->shopify_orders_address->city ?? '',
                        'address'   => $order->shopify_orders_address->address1 . $order->shopify_orders_address->address2 ?? '',
                        'postcode'  => $order->shopify_orders_address->zip ?? '',
                        'phone'     => $order->shopify_orders_address->phone ?? '',
                    ];

                    //创建消费订单
                    $customerOrderObj = CustomerOrder::query()->create($customerOrder);
                    $customerOrderObj->detail()->createMany($customerOrderDetail);
                    $customerOrderObj->receiver()->create($customerOrderReceiver);

                    //更新乐天订单
                    $order->erp_sync = ShopifyOrder::SYNC_YES;//同步正常
                    $order->save();

                    $logData[] = $order_no;
                    $i++;
                }
            }

            //添加日志
            $totalCount = $i;
            ShopifyLogs::logs(ShopifyLogs::$customerOrderException, date('Y-m-d H:i:s', time()).',['. $totalCount .']条,消费者异常订单同步成功!', $logData);
            DB::commit();

        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * （向shopify平台回写订单物流数据）
     * 同步独立站订单的物流追踪号
     * @param string $shop 'UNG','ORG'
     * @return null
     */
    public static function syncShopifyOrderTrackingNo($shop = 'UNG'){

        //参数
        if(!in_array($shop, self::$_shop)) die(0);

        //$createdAtMin = strtotime('2022-01-01');
        //if(!$createdAtMin) return null;
        //
        //$con = [];
        //$con['created_at_min'] = getDateFormat(date('Y-m-d H:i:s', $createdAtMin), 'PRC', 'Y-m-d\TH:i:sP');
        //$createAtMax = $createdAtMin + self::GRAB_ORDERS_INTERVAL;
        //if($createAtMax > time()){
        //    $createAtMax = time();
        //}
        //$con['created_at_max'] = getDateFormat(date('Y-m-d H:i:s', $createAtMax), 'PRC', 'Y-m-d\TH:i:sP');
        //$con['limit'] = 50;
        //$con['status'] = 'any';
        //$con['fields'] = 'id,email,created_at,name,total_line_items_price,total_discounts,total-price,currency,line_items,shipping_lines,shipping_address,fulfillments';
        //$con['start_time'] = $createdAtMin;


        $data = json_decode('{"fulfillment":{"line_items_by_fulfillment_order":[{"fulfillment_order_id":1046000796}],"tracking_info":{"number":"1Z001985YW99744790"}}}',true);
       // dd($data);
       // dd([
       //     'fulfillment' => [
       //         'line_items_by_fulfillment_order' => [
       //             [
       //                 "fulfillment_order_id" => 13911831609586
       //             ]
       //         ],
       //         'tracking_info' => [
       //             "number" => "TBA313598994634"
       //         ]
       //     ]
       // ]);
        //获取订单(带分页数据)

        $client = self::getRequestClient($shop);
        //$pagination = $client->getOrderManager()->find(5057891795186); //UG6896
        //$pagination = $client->getOrderManager()->find(5636057432306); // UG7952
        $pagination = $client->getFulfillmentManager()->findAll(5057891795186);
        dd($pagination);
        dd($pagination->getFulfillments());


        $pagination = $client->getFulfillmentManager()->create(
            5636057432306,
            [
                "fulfillment" => [
                    "line_items_by_fulfillment_order" => [
                        ["fulfillment_order_id" => 13911831609586],
                        //["fulfillment_order_line_items"] => [
                        //    "id" => 1,
                        //    "quantity" => 1
                        //]
                    ],
                    "tracking_info" => [
                        "number" => "TBA313598994634"
                    ]
                ]
            ]
        );
        dd($pagination);
        dd($pagination->toarray());
    }

}
